/**
 * Copyright (C)  Gadglet .
 *
 * This file is part of Gadglet
 *
 * Gadglet is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Gadglet is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with Gadglet. If not, see <http://www.gnu.org/licenses/>.
 */

package com.gadglet.servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.gadglet.core.GadgletRequestWrapper;
import com.gadglet.core.GadgletResponse;
import com.gadglet.core.RequestException;
import com.gadglet.data.Gadget;
import com.gadglet.data.GadgetUtils;
import com.gadglet.data.UserProfile;
import com.gadglet.data.UserProfilesUtils;
import com.gadglet.params.GadgetType;
import com.gadglet.params.ReqActionTypes;
import com.gadglet.params.ReqErrorTypes;
import com.gadglet.util.UrlUtils;
import com.google.gson.Gson;

public class SignedRequestServlet extends BasicRequestServlet {
	/**
	 * This servlet will be used for Gadgets using simple igoogle account (not
	 * google apps) the servlet only check the validity without knowing the User
	 * identity
	 */
	private static final long serialVersionUID = 17583894573489L;
	Logger log = Logger.getLogger(this.getClass().getName());

	@Override
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		checkUser(request, response);
		

	}

	@Override
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		
		checkUser(request, response);
		
	}

	private void checkUser(HttpServletRequest httpServletRequest,
			HttpServletResponse httpServletResponse) {
		GadgletResponse gadgetServerResponse = new GadgletResponse();
		GadgletRequestWrapper platformRequestWrapper = new GadgletRequestWrapper(
				httpServletRequest);
		boolean userIsValid = true;
		UserProfile userProfile = null;

		if (!(platformRequestWrapper.getParameter("ignoreJson") != null && UrlUtils
				.isOnDevPort8888(platformRequestWrapper)))
			setResponseHeaders(httpServletResponse);

		try {
			if (platformRequestWrapper.getOpenSocialConsumerKey() == null) {
				log.warning("oauth_consumer_key is null");
				throw new RequestException(ReqErrorTypes.UNSUPPORETED_PLATFORM);
			}
			if (platformRequestWrapper.getOpenSocialViewerId() == null) {
				log.warning("opensocial_viewer_id is null");
				throw new RequestException(ReqErrorTypes.USER_NOT_LOGGEDIN);
			}

			if (!UrlUtils.isOnDevPort8888(platformRequestWrapper)
					&& !validateSignedRequestWithContainer(platformRequestWrapper)) {
				throw new RequestException(ReqErrorTypes.USER_NOT_LOGGEDIN);
			}

			if (platformRequestWrapper.getCurrentUserProfile() != null){
				// check if user changed in session the middle ?
				userProfile = platformRequestWrapper.getCurrentUserProfile();
				
				if(!userProfile.getOpenSocialViewerId().equals(platformRequestWrapper.getOpenSocialViewerId()))
					platformRequestWrapper.getSession().setAttribute(
							"userProfile", null);
			}
			
			if (platformRequestWrapper.getCurrentUserProfile() == null) {

				userProfile = UserProfilesUtils
						.getMyProfile(platformRequestWrapper);
				if (userProfile != null){
					platformRequestWrapper.getSession().setAttribute(
							"userProfile", userProfile);
					
					userIsValid = true;
				}
				else if (platformRequestWrapper.getGadgetActionType().equals(
						ReqActionTypes.ADD_PROFILE))
					userIsValid = true; // proceed to profile creation
				else
					throw new RequestException(
							ReqErrorTypes.PROFILE_DOESNT_EXISTS);
			}
			else
				userIsValid = true;
			
			// load gadget
			Gadget g = GadgetUtils.getGadget(platformRequestWrapper.getGadgetName());
			if(g==null || g.getGadgletType()==null || !g.getGadgletType().equals(GadgetType.MINGLET.getGadgetType()))
				throw new RequestException(
						ReqErrorTypes.UNRECOGNIZED_GADGET);
			else
				platformRequestWrapper.setRequestedGadget(g);
			
			
		} catch (RequestException e) {
			userIsValid = false;
			gadgetServerResponse.setError(e);
		} catch (Exception e) {
			userIsValid = false;
			printStackTrace(e);
			gadgetServerResponse.setError(new RequestException(
					ReqErrorTypes.REQUEST_FAILED));
		}

		if (userIsValid)
			performRequest(platformRequestWrapper, gadgetServerResponse,
					httpServletResponse);
		else {
			PrintWriter out = null;
			try {
				out = httpServletResponse.getWriter();
				Gson gson = new Gson();
				out.print(gson.toJson(new JsonEnvelope(gadgetServerResponse)));
			} catch (IOException e) {

				log.warning(e.getMessage());
			}

		}

	}

}
